package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDtao;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/7 14:43
 * @Version 1.0
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDtao loginDtao) {

        if(!StringUtils.isEmpty(loginDtao.getPhone()) && !StringUtils.isEmpty(loginDtao.getPassword())){
            //查询：根据电话
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDtao.getPhone()));
            //判断用户是否存在
            if(apUser == null){
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //校验密码
            String srcPassword = DigestUtils.md5DigestAsHex((loginDtao.getPassword() + apUser.getSalt()).getBytes());
            if(!srcPassword.equals(apUser.getPassword())){
                throw new CustomException(AppHttpCodeEnum.LOGIN_ERROR);
            }
            //封装返回参数
            Map<String,Object> map  = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        } else {
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            Object userId = claimsBody.get("id");
            return ResponseResult.okResult(map);
        }

    }

    @Override
    public ResponseResult info(Integer userId) {
        // 1.参数检测
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.查询
        ApUser user = getById(userId);

        // 3.覆盖关键信息
        user.setPassword("");
        user.setSalt("");

        // 4.返回
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult getUser(Integer id) {
        ApUser user = getById(id);
        return ResponseResult.okResult(user.toString());
    }
}